<template>
  <t-card title="邮件发送" :bordered="true" style="height: 100%; width: 100%;">
    <!--  scrollToFirstError="smooth" -->
    <t-form ref="form" :data="formData" :rules="rules" @reset="onReset" @submit="onSubmit"
      style="margin-bottom: 20px ;">
      <t-form-item label="服务器" name="server">
        <div style="display: flex; align-items: center; gap: 10px;">
          <t-space>
            <!-- 开启虚拟滚动 请为select的panel设定好height 通过popupProps进行透传 -->
            <t-select v-model="formData.server" :loading="serverLoading" :options="serverOptions.value" filterable
              placeholder="请选择" style="width: 300px" :scroll="{ type: 'virtual' }">
            </t-select>
          </t-space>
        </div>
      </t-form-item>

      <t-form-item label="uids" help="支持多个uid" name="uids">
        <t-tag-input :onBlur="handleBlur" excess-tags-display-type="break-line" v-model="formData.uids" clearable
          style="width: 25%;" />
      </t-form-item>

      <t-form-item label="类型" name="mailType">
        <t-radio-group v-model="formData.mailType">
          <t-radio value="sausage">吃鸡邮件</t-radio>
          <t-radio value="golddash">打金邮件</t-radio>
        </t-radio-group>
      </t-form-item>

      <div v-for="(item, index) in selectItems" :key="index" style="margin-bottom: 10px; display: block;">
        <t-form-item :label="'物品' + (index + 1)" name="items">
          <div style="display: flex; align-items: center; gap: 10px;">
            <t-space>
              <!-- 开启虚拟滚动 请为select的panel设定好height 通过popupProps进行透传 -->
              <t-select v-model="selectItems[index].value" :options="options" filterable placeholder="请选择"
                style="width: 300px" :scroll="{ type: 'virtual' }" />
            </t-space>
            <t-input-number v-model="selectItems[index].num" style="min-width: 180px;" />
            <t-button theme="danger" @click="removeSelect(index)" style="margin-left: 10px;">
              删除
            </t-button>
          </div>
        </t-form-item>
      </div>

      <t-form-item>
        <t-space size="small">
          <t-button @click="addSelect">
            <t-icon name="add" /> 添加物品
          </t-button>
        </t-space>


      </t-form-item>
      <t-form-item>
        <t-space size="small">
          <t-button :loading="sendLoading" theme="primary" type="submit">发送</t-button>
          <t-button theme="default" variant="base" type="reset">重置</t-button>
        </t-space>
      </t-form-item>
    </t-form>
    <t-space direction="vertical">
      <t-card title="玩家基建等级" bordered>
        <t-form ref="form" :data="formData" :rules="rules" @submit="stationOnSubmit"
          style="margin-bottom: 20px ;">
          <t-form-item v-for="item in stationList" :key="item.id" :label="item.name">
            <div style="display: flex; align-items: center; gap: 10px;">
              <t-input-number v-model="stationLevels[item.id]" style="min-width: 180px;" />
              <t-button theme="primary" @click="stationOnSubmit('infrastructure',item.id,stationLevels[item.id])" style="margin-left: 10px;">
                发送
              </t-button>
            </div>
          </t-form-item>
        </t-form>
      </t-card>
    </t-space>
  </t-card>
</template>
<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { useRouter } from 'vue-router';
import { fetchServerData, fetchItemData, RequestSendMail, RequestGodSkill } from '@/composables/usePax'
import { useServer } from '@/stores/pax.ts'
import { storeToRefs } from 'pinia'
const serverStore = useServer()
const { serverList } = storeToRefs(serverStore) // 保持响应式
const selectItems = ref([{ value: '', num: 1 }]); // 初始一个空选择器，带数量
const ItemLoading = ref(true);
const serverLoading = ref(true);
const sendLoading = ref(false);
const stationList = [
  { name: "天赋", id: "1942428078038847488" },
  { name: "战备库", id: "1934861928362938368" },
  { name: "鼠鼠洞", id: "1935263827901812736" },
  { name: "宠物中心", id: "1935263129407590400" },
]
const stationLevels = ref({});

// 初始化每个站点的默认值为1
stationList.forEach(station => {
  stationLevels.value[station.id] = 1;
});
// 获取 t-tag-input 的 DOM 引用
const uidInputRef = ref('null');
const router = useRouter() // 获取路由实例
const formData = reactive({
  server: 's1',
  uids: [],
  mailType: 'sausage',
  num: 1,
});
const skillFormData = reactive({
  server: '',
  uid: '',
});

const rules = {
  server: [
    { required: true, message: '服务器必填', type: 'error', trigger: 'error' },
    { whitespace: true, message: '服务器不能为空' },
  ],
  uids: [
    { required: true, message: 'uid必填', type: 'error' },
    { whitespace: true, message: 'uid能为空' },
  ],
};
const handleBlur = (value, context) => {
  const inputValue = context.inputValue;
  if (inputValue) {
    formData.uids.push(inputValue.trim());
  }
}

const options = ref([]); // 初始为空，稍后填充;
const serverOptions = ref([]); // 所有数据（缓存）
const golddash_items = ref([])
const sausage_items = ref([])
// 在组件加载时请求数据
onMounted(async () => {
  ItemLoading.value = true;
  try {
    // 获取 服务器 信息
    serverOptions.value = ref(serverList)

    const ServerData = await fetchServerData()
    serverOptions.value = ref(ServerData.value.data)

    // 获取 物品 信息

    const ItemData = await fetchItemData({ server: formData.server })
    if (formData.mailType === 'golddash') {
      golddash_items.value = ItemData.value.golddash_items;
      options.value = ItemData.value.golddash_items;
    } else if (formData.mailType === 'sausage') {
      options.value = ItemData.value.sausage_items;
    }
    sausage_items.value = ItemData.value.sausage_items;
    golddash_items.value = ItemData.value.golddash_items;
  } catch (error) {
    MessagePlugin.error('物品加载失败');
    setTimeout(() => {
      router.push('/login'), 1000
    })
  } finally {
    ItemLoading.value = false;
    serverLoading.value = false
  }
});
// 在 onMounted 之后添加监听逻辑
watch(
  () => formData.mailType,  // 监听 mailType 的变化
  (newMailType) => {
    // 1. 立即清空 options（避免显示旧数据）
    options.value = []; // 清空选项
    selectItems.value = [{ value: '', num: 1 }]; // 重置为初始状态（一个空选择器）
    // 当 mailType 变化时，重新请求接口
    switchItemsByMailType(newMailType);
  }
);

watch(
  () => formData.server,  // 监听 mailType 的变化
  () => {
    // 1. 立即清空 options（避免显示旧数据）
    options.value = []; // 清空选项
    selectItems.value = [{ value: '', num: 1 }]; // 重置为初始状态（一个空选择器）
    // 当 mailType 变化时，重新请求接口
    fetchItemsByMailType(formData.mailType);
  }
);

const switchItemsByMailType = function (mailType) {
  if (mailType === 'golddash') {
    options.value = golddash_items.value; // 更新为打金邮件数据
  } else if (mailType === 'sausage') {
    options.value = sausage_items.value; // 更新为吃鸡邮件数据
  }
};
// 定义请求函数
const fetchItemsByMailType = async (mailType) => {
  ItemLoading.value = true;
  try {
    const ItemData = await fetchItemData({ server: formData.server })
    if (mailType === 'golddash') {
      options.value = golddash_items.value; // 更新为打金邮件数据
    } else if (mailType === 'sausage') {
      options.value = sausage_items.value; // 更新为吃鸡邮件数据
    }
    sausage_items.value = ItemData.value.sausage_items;
    golddash_items.value = ItemData.value.golddash_items;

  } catch (error) {
    MessagePlugin.error('加载选项失败，请稍后重试');
  } finally {
    ItemLoading.value = false;
  }
};


const onReset = () => {

  // 2. 手动设置 mailType 的默认值
  formData.mailType = 'sausage'; // 默认勾选"吃鸡邮件"

  // 3. 可选：重置其他数据（如 selectItems）
  selectItems.value = [{ value: '', num: 1 }];
  MessagePlugin.success('重置成功');
};


const onSubmit = async ({ validateResult, firstError, e }) => {
  e.preventDefault();
  if (validateResult === true) {
    const attachments = [];
    const server = formData.server;
    const uids = formData.uids;
    const mailType = formData.mailType;
    const token = localStorage.getItem('pax_token');
    // Process each selected item
    selectItems.value.forEach(item => {
      if (item.value) { // Only process items that have a selected value
        const quantity = item.num;
        const itemId = item.value;

        if (mailType === 'golddash') {
          attachments.push({
            Num: parseInt(quantity) || 1,
            ItemId: itemId,
            wear: 0,
            entry1: 0,
            entry2: 0,
            entry3: 0,
            entry4: 0,
            mail_item_type: 1
          });
        } else {
          attachments.push({
            Num: parseInt(quantity) || 1,
            ItemId: itemId,
            wear: 0,
            uuid: "0",
            mail_item_type: 0
          });
        }
      }
    });
    try {
      sendLoading.value = true
      const response = await RequestSendMail({
        server_name: server,
        uids: uids.join(','),
        attachments: attachments,
        token: token,
        mail_type: mailType
      })
      const data = response.value;
      if (data.success) {
        MessagePlugin.success('发送成功');
      } else {
        MessagePlugin.error('发送失败');
      }
    } catch (error) {
      console.log(`发送失败${error}`)
      MessagePlugin.error('发送失败');
      const { status, data } = error.response
      if (status === 401) {
        MessagePlugin.error('token过期，即将跳转登录界面');
        localStorage.removeItem('pax_token')
        setTimeout(() => {
          router.push('/login')
        }, 1000)

      }
    }
    sendLoading.value = false

  } else {
    MessagePlugin.warning(firstError);
  }
};
const stationOnSubmit = async (query_key, infra_id, infra_level) => { 
  
  const res = await RequestGodSkill(
    {
      server_name: formData.server,
      uid: formData.uids[0],
      query_key,
      infra_id,
      infra_level
    }
  )
  const data = res.value;
  if (data.success) {
    MessagePlugin.success('执行成功');
  } else {
    MessagePlugin.error('执行失败');
  }
}
const handleClear = () => {
  form.value.clearValidate();
};

const addSelect = () => {
  selectItems.value.push({ value: '', num: 1 }); // 添加新选择器
};

const removeSelect = (index) => {
  selectItems.value.splice(index, 1); // 删除选择器
};

</script>
<style scoped></style>
